<?php
namespace AdminBundle\Model;

use AdminBundle\Entity\Menu;
use RedUnicorn\SymfonyKernel\Appoint\Model\BuiltInDataInterface;
use RedUnicorn\SymfonyKernel\Model\Model;
use Symfony\Component\DependencyInjection\ContainerInterface;

class m_menu extends Model implements BuiltInDataInterface
{
    private $menus = [
//        //增加一级菜单
//        ['title' => '菜单标题', 'url' => '路由名', 'url_params' => ['参数key' => '参数value'], 'tag' => '菜单标记', 'icon' => '图标'],
//        //增加二级菜单
//        ['title' => '模块标题', 'icon' => '图标', 'children' => [
//            ['title' => '菜单标题', 'url' => '路由名', 'url_params' => ['参数key' => '参数value'], 'tag' => '菜单标记'],
//        ]],
        ['title' => '权限管理', 'icon' => 'icon-lock', 'children' => [
            ['title' => '权限分配', 'url' => 'admin_assignment_list', 'url_params' => [], 'tag' => 'assignments'],
        ]],
        ['title' => '文章管理', 'url' => '', 'tag' => '', 'icon' => 'icon-folder-close', 'children' => [
            ['title' => '文章分类管理', 'url' => 'admin_article_class_list', 'tag' => 'article_classes'],
            ['title' => '文章管理', 'url' => 'admin_article_list', 'tag' => 'articles'],
        ]]
    ];

    public function __construct(ContainerInterface $container = null)
    {
        parent::__construct($container, 'menu');
    }

    public function validate($data, $id = false)
    {
        return true;
    }

    public function insert($data)
    {
        return true;
    }

    function update($id, $data)
    {
        return true;
    }

    public function builtInData()
    {
        // 清空menu
        self::$conn->executeUpdate('TRUNCATE menu');

        $this->generateMenu($this->menus);
    }

    private function generateMenu($menus, $parent_id = 0)
    {
        $sort_order = 1;

        foreach ($menus as $v) {
            $menu = new Menu();
            $menu->setIcon(isset($v['icon']) ? $v['icon'] : '');
            $menu->setTitle(isset($v['title']) ? $v['title'] : '');
            $menu->setUrl(isset($v['url']) ? $v['url'] : '');
            $menu->setTag(isset($v['tag']) ? $v['tag'] : '');
            $menu->setUrlParams(isset($v['url_params']) ? serialize($v['url_params']) : '');
            $menu->setSortOrder($sort_order);
            $menu->setIsBindPermission(false);
            $menu->setParentId($parent_id);

            $sort_order++;

            if ($result = $this->getDoctrine()
                ->getRepository(Menu::class)
                ->findOneBy(array('tag' => $menu->getTag(), 'title' => $menu->getTitle()))
            ) {
                $menu = $result;
            } else {
                $em = $this->getDoctrine()->getManager();
                $em->persist($menu);
                $em->flush();
            }

            if (isset($v['children'])) {
                $this->generateMenu($v['children'], $menu->getId());
            }
        }
    }
}